<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HTML5 IndexedDB</title>
<script src="../js/jquery-1.8.3.js"></script>
<script type="text/javascript">
	var localDatabase = {};
	var dbName = "msgdb";//数据库名字
	var storeName = "msginfo";//存储空间名字
	var version = 1;//版本号
	var totalMsg = 0;// 消息数量
	localDatabase.indexedDB = window.indexedDB || window.mozIndexedDB
			|| window.webkitIndexedDB || window.msIndexedDB;//对应浏览器版本
	localDatabase.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;//范围
	localDatabase.IDBTransaction = window.IDBTransaction
			|| window.webkitIDBTransaction;//事务

	localDatabase.indexedDB.onerror = function(e) {
		console.log("Database error: " + e.target.errorCode);
	};

	$(function() {

		var openRequest = localDatabase.indexedDB.open(dbName, 1);

		openRequest.onerror = function(e) {
			console.log("Database error: " + e.target.errorCode);
		};
		openRequest.onsuccess = function(event) {
			console.log("Database created");
			localDatabase.db = openRequest.result;
			var db = event.target.result;
			useDatabase(db);
		};

		//唯一可以修改数据库结构的地方。触发的时机是？
		openRequest.onupgradeneeded = function(evt) {
			console.log("I need to create the objectstore");
			//创建名为storeName变量值的对象存储空间
			var objectStore = evt.currentTarget.result.createObjectStore(
					storeName, {
						keyPath : "id",
						autoIncrement : true
					});
			objectStore.createIndex("firstNameIndex", "first_name", {
				unique : false
			});//就是一个索引  但是可以是属性的对象的名字
			objectStore.createIndex("lastNameIndex", "last_name", {
				unique : false
			});
		};

		//页面加载完成就执行的部分-begin
	});
	
	function useDatabase(db) {
		// 确保添加一个如果另一个页面请求一个版本变化时来被通知的处理程序。
		// 我们必须关闭这个数据库。这就允许其他页面对数据库进行升级。
		// 如果你不这么做的话，除非用户关闭标签页否则升级就不会发生。
		db.onversionchange = function(event) {
			db.close();
			alert("A new version of this page is ready. Please reload!");
		};

		// 其他针对数据库的处理
	}
	
	// 删除数据库
	function delDatabase() {
		console.log('Deleting local database');
		var deleteDbRequest = localDatabase.indexedDB.deleteDatabase(dbName);
		deleteDbRequest.onsuccess = function(event) {
			console.log('Database deleted');
			var openRequest = localDatabase.indexedDB.open(dbName, 1);
		};

		deleteDbRequest.onerror = function(e) {
			console.log("Database error: " + e.target.errorCode);
		};
	}

	// 添加记录
	function add() {
		try {
			//readwrite 赋予读写权限
			var transaction = localDatabase.db.transaction(storeName,
					"readwrite");
			var store = transaction.objectStore(storeName);

			if (localDatabase != null && localDatabase.db != null) {

				var in_txt = $("#txtinput").val();
				try {
					var in_txt_json = JSON.parse(in_txt);
				} catch (e) {
					console.log(e);
					console.log("要转换的json字符串格式不正确！！！！！！！！");
					$("#log").append("要转换的json字符串格式不正确！！！！！！！！").append(
							"<br />");
					return;
				}

				var request = store.put(in_txt_json);

				request.onsuccess = function(e) {
					console.log("Added " + in_txt);
					$("#log").append("插入记录成功 ==> " + in_txt).append("<br />");
				};

				request.onerror = function(e) {
					console.log(e.value);
				};

			}

		} catch (e) {
			console.log(e);
		}
	}

	//查询记录
	function fetchById() {
		try {
			if (localDatabase != null && localDatabase.db != null) {
				//transaction 不加第二个参数，默认为只读(read-only)权限
				var store = localDatabase.db.transaction(storeName)
						.objectStore(storeName);
				/* store.get($("#txtSearchById").val()).onsuccess = function(event) {
					var r_data = event.target.result;
					if (r_data == null) {
						$("#log").append("未查询到记录！").append("<br />");
					} else {
						var jsonStr = JSON.stringify(r_data);
						$("#log").append("查询记录 ==>" + jsonStr).append("<br />");
					}
				}; */
				
				var request = store.get($("#txtSearchById").val());

				request.onsuccess = function(e) {
					var r_data = event.target.result;
					if (r_data == null) {
						$("#log").append("未查询到记录！").append("<br />");
					} else {
						var jsonStr = JSON.stringify(r_data);
						$("#log").append("查询记录 ==>" + jsonStr).append("<br />");
					}
				};

				request.onerror = function(e) {
					$("#log").append("查询出现异常！").append("<br />");
				};
			}
		} catch (e) {
			console.log(e);
		}
	}

	function fetchByIndex() {
		
		try {
			if (localDatabase != null && localDatabase.db != null) {
				//transaction 不加第二个参数，默认为只读(read-only)权限
				
				var range = IDBKeyRange.only($("#txtSearchByIndexValue").val());
				
				var store = localDatabase.db.transaction(storeName)
						.objectStore(storeName);
				
				var request = store.index($("#txtSearchByIndex").val());

				request.openCursor(range).onsuccess = function(evt) {  
				    var cursor = evt.target.result;    
				    if (cursor) {
				    	var employee = cursor.value;
				    	var jsonStr = JSON.stringify(employee);
				    	$("#log").append("查询记录 ==>" + jsonStr).append("<br />");  
				        cursor.continue();  
				    }  
				};
				
				request.onerror = function(e) {
					$("#log").append("查询出现异常！").append("<br />");
				};
			}
		} catch (e) {
			console.log(e);
		}
	}
	
	//修改记录
	function updateById() {
		try {
			if (localDatabase != null && localDatabase.db != null) {
				var store = localDatabase.db
						.transaction(storeName, "readwrite").objectStore(
								storeName);
				store.get($("#txtUpdateById").val()).onsuccess = function(event) {
					var r_data = event.target.result;
					if (r_data == null) {
						$("#log").append("未查询到记录！").append("<br />");
					} else {

						// 修改first_name属性值
						r_data.first_name = $("#txtFirstName").val();
						var jsonStr = JSON.stringify(r_data);

						// 将修改后的记录更新到store
						var request = store.put(r_data);

						request.onsuccess = function(e) {
							$("#log").append("修改记录成功 ==> " + jsonStr).append(
									"<br />");
						};

						request.onerror = function(e) {
							$("#log").append("修改记录失败 ==> " + e.value).append(
									"<br />");
							console.log("修改记录失败 ==> " + e.value);
						};
					}
				};
			}
		} catch (e) {
			console.log(e);
		}
	}
	
	//删除记录
	function delById() {
		try {
			if (localDatabase != null && localDatabase.db != null) {
				var store = localDatabase.db
						.transaction(storeName, "readwrite").objectStore(
								storeName);
				// 删除store
				var request = store.delete($("#txtDelById").val());
				
				request.onsuccess = function(e) {
					$("#log").append("删除记录成功 ==> " + $("#txtDelById").val()).append(
							"<br />");
				};

				request.onerror = function(e) {
					$("#log").append("删除记录失败 ==> " + e.value).append(
							"<br />");
					console.log("删除记录失败 ==> " + e.value);
				};
			}
		} catch (e) {
			console.log(e);
		}
	}

</script>
</head>

<body>

	<textarea rows="5" cols="100" id="txtinput">{"id" : "E1","first_name" : "Joe","last_name" : "Smith"}</textarea>
	<br />
	<br />
	<button type="button" id="btnAdd" onclick="add()">添加一行记录</button>
	<hr>
	
	<span>查询id=</span>
	<input type="text" id="txtSearchById" />
	<span>的记录</span>
	<button type="button" id="btnSearch" onclick="fetchById()">查询</button>
	<hr>
	
	<span>查询索引=</span>
	<input type="text" id="txtSearchByIndex" />
	<span>key 值=</span>
	<input type="text" id="txtSearchByIndexValue" />
	<span>的记录</span>
	<button type="button" id="btnSearchByIndex" onclick="fetchByIndex()">查询</button>
	<hr>
	
	<span>查询id=</span>
	<input type="text" id="txtUpdateById" />
	<span>的记录，将first_name属性修改为</span>
	<input type="text" id="txtFirstName" />
	<button type="button" id="btnUpdate" onclick="updateById()">修改</button>
	<hr>
	
	<span>删除id=</span>
	<input type="text" id="txtDelById" />
	<span>的记录</span>
	<button type="button" id="btnUpdate" onclick="delById()">删除</button>
	<hr>
	
	<div id="log"></div>

</body>
</html>